<?php
    require_once 'global.php';
    require_once 'db.php';

    $failed = false;
    if (isset($_POST['register']))
    {
        if (!isset($_POST['company']))
        {   
            if (isset($_POST['username'])
                && isset($_POST['passwd'])
                && isset($_POST['companyid'])
                && isset($_POST['typeid'])
                && isset($_POST['email']))
            {
                $username = $_POST['username'];
                $password = md5($_POST['passwd']);
                $companyid = $_POST['companyid'];
                $typeid = $_POST['typeid'];
                $email = $_POST['email'];
    
                $sql = "insert into users (username, password, companyid, typeid, email) values (\"$username\", \"$password\", \"$companyid\", \"$typeid\", \"$email\");";
                $result = $db->query($sql); 
                
                if ($result == 1)
                {
                    header("Location:index.php");
                    //echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">注册成功<br><a href=/login.php>登录</a>";
                    exit(0);
                }
                else
                {
                    $failed = true;
                }
            }
        }else
        {
            if (isset($_POST['name'])
                && isset($_POST['owner'])
                && isset($_POST['tel']))
            {
                $name = $_POST['name'];
                $owner = $_POST['owner'];
                $tel = $_POST['tel'];
                
                $sql = "insert into company (name, owner, telephone) values (\"$name\", \"$owner\", \"$tel\");";
                $result = $db->query($sql); 
                
                if ($result == 1)
                {
                    header("Location:index.php");
                    //echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">注册成功<br><a href=/login.php>登录</a>";
                    exit(0);
                }
                else
                {
                    $failed = true;
                }
            }
         }
    }
    
    $sql = "select id, name from company";
    $companys = $db->fetchAll($sql);
    
    if (isset($_GET['type']))
    {
        $type = $_GET['type'];
    }
    else 
    {
        $type = "user";
    }
    
    include("templates/register.html");
?>
